﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Gmmy.Utility;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Surging.Core.Caching;
using Surging.Core.CPlatform.Cache;
using Surging.Core.ProxyGenerator;

namespace ApiGateway.Controllers
{
    [Route("api/[controller]")]
    public class SwaggerJson : Controller
    {
        private readonly ICacheProvider _cacheProvider;
        private readonly IServiceProxyProvider _serviceProxyProvider;
        public List<string> SwaggerRoots { get; set; }
        public SwaggerJson(IServiceProxyProvider serviceProxyProvider)
        {
            _serviceProxyProvider = serviceProxyProvider;
            _cacheProvider = CacheContainer.GetService<ICacheProvider>("ddlCache.Redis");
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory() + "/Configs/").
                AddJsonFile("gatewaySettings.json");
            var config = builder.Build();
            SwaggerRoots = config.GetSection("SwaggerServices").Value.Split(',').ToList();
        }
        [HttpGet]
        public async Task<dynamic> Get()
        {
            var json = new swaggerJsonDto()
            {
                info = new info()
                {
                    title = "微服务网关API文档",
                    version = "v1.0.0"
                },
                swagger = "2.0"
            };
            var paths = new Dictionary<string, object>();
            var definitions = new Dictionary<string, object>();
            if (SwaggerRoots.Any())
            {
                foreach (var root in SwaggerRoots)
                {
                    var item = await GetServiceSwaggerJson(root);
                    if (item != null)
                    {
                        foreach (var keyValuePair in item.paths)
                        {
                            if (!paths.ContainsKey(keyValuePair.Key))
                            {
                                paths.Add(keyValuePair.Key, keyValuePair.Value);
                            }
                        }
                        foreach (var keyValuePair in item.definitions)
                        {
                            if (!definitions.ContainsKey(keyValuePair.Key))
                            {
                                definitions.Add(keyValuePair.Key, keyValuePair.Value);
                            }
                        }
                    }
                }
            }
            json.paths = paths;
            json.definitions = definitions;
            return json;
        }

        public async Task<swaggerJsonDto> GetServiceSwaggerJson(string root)
        {
            try
            {
                var proxyResult = await _serviceProxyProvider.Invoke<swaggerJsonDto>(new Dictionary<string, object>(), $"api/{root}/swagger/get");
                if (proxyResult != null)
                {
                    return proxyResult;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine($"json文件读取失败,服务路由:{root},失败原因:{e.Message}");
            }
            return null;
        }
    }


}
